package com.xcm.util;

import com.obs.services.ObsClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * @author dxy
 */
public class HuaWeiCloudUtils {
	private static Logger logger = LoggerFactory.getLogger(HuaWeiCloudUtils.class);
	/**
	 * Access Key Id
	 */
	private static final String HUAWEI_OSS_AK = "3GH3IVJKGFEUMF5WLOQQ";
	/**
	 * 桶名称
	 */
	private static final String HUAWEI_OSS_BUCKET_NAME = "obs-222f";
	/**
	 * 域名
	 */
	private static final String HUAWEI_OSS_ENDPOINT = "obs.cn-south-1.myhwclouds.com";
	/**
	 * Secret Access Key
	 */
	private static final String HUAWEI_OSS_SK = "1N4whT7W6IgSp0Q7kjfgqeOjI2fT1OAWHpkXTeww";

	/**
	 * 上传文件到华为云
	 *
	 * @param multipartFile MultipartFile
	 * @param fileDir       文件目录（如"xcpis/apk/"）
	 * @return String(文件下载地址)
	 */
	public static String uploadFile2HuaweiCloud(MultipartFile multipartFile, String fileDir) throws IOException {
		//文件保存地址
		String fileSaveUrl = "";
		//创建ObsClient实例,自动关闭流
		try (ObsClient obsClient = new ObsClient(HUAWEI_OSS_AK, HUAWEI_OSS_SK, HUAWEI_OSS_ENDPOINT)) {
			//判断桶是否存在，不存在就创建
			boolean exists = obsClient.headBucket(HUAWEI_OSS_BUCKET_NAME);
			if (!exists) {
				//创建桶
				obsClient.createBucket(HUAWEI_OSS_BUCKET_NAME);
			}
			//文件保存路径
			String filePath = fileDir + multipartFile.getOriginalFilename();
			//上传文件到华为云
			obsClient.putObject(HUAWEI_OSS_BUCKET_NAME, filePath, new ByteArrayInputStream(multipartFile.getBytes()));
			//文件保存路径
			fileSaveUrl = "https://" + HUAWEI_OSS_BUCKET_NAME + "." + HUAWEI_OSS_ENDPOINT + "/" + filePath;
		} catch (IOException e) {
			e.printStackTrace();
			logger.error("HuaWeiCloudUtils uploadFile2HuaweiCloud 上传文件到华为云失败：" + e.getMessage());
			throw e;
		}
		return fileSaveUrl;
	}

	/**
	 * 上传文件到华为云
	 *
	 * @param file File
	 * @param fileDir       文件目录（如"xcpis/apk/"）
	 * @return String(文件下载地址)
	 */
	public static String uploadFile2HuaweiCloud(File file, String fileDir) throws IOException {
		//文件保存地址
		String fileSaveUrl = "";
		//创建ObsClient实例,自动关闭流
		try (ObsClient obsClient = new ObsClient(HUAWEI_OSS_AK, HUAWEI_OSS_SK, HUAWEI_OSS_ENDPOINT)) {
			//判断桶是否存在，不存在就创建
			boolean exists = obsClient.headBucket(HUAWEI_OSS_BUCKET_NAME);
			if (!exists) {
				//创建桶
				obsClient.createBucket(HUAWEI_OSS_BUCKET_NAME);
			}
			//文件保存路径
			String filePath = fileDir + file.getName();
			//上传文件到华为云
			obsClient.putObject(HUAWEI_OSS_BUCKET_NAME, filePath, new FileInputStream(file));
			//文件保存路径
			fileSaveUrl = "https://" + HUAWEI_OSS_BUCKET_NAME + "." + HUAWEI_OSS_ENDPOINT + "/" + filePath;
		} catch (IOException e) {
			e.printStackTrace();
			logger.error("HuaWeiCloudUtils uploadFile2HuaweiCloud 上传文件到华为云失败：" + e.getMessage());
			throw e;
		}
		return fileSaveUrl;
	}
}
